<template>
	<view class="wanlshop-container">
		<view v-if="common.modulesData.homeModules.page" class="wanlshop-container__head" :style="{
				height: headHeight + 'px',
				color: '#ffffff',
				backgroundColor: common.modulesData.homeModules.page ? common.modulesData.homeModules.page.style.navigationBarBackgroundColor : '#f7f7f7'
			}">
			<view :style="{ height: headHeight + 'px', paddingTop: headTop + 'px' }">
				<view class="navigater flex align-center justify-between address">
					<view class="flex">
						<view class="text-df flex" @tap="$wanlshop.to('/pages/page/city')">
							<!-- <text class="wlIcon-sheng"></text> -->
							<text>{{common.addressText}}</text>
							<text style="margin-top: 10rpx;" class="wlIcon-jiang text-df margin-top"></text>
						</view>
					</view>
					<view class="search flex align-center margin-lr-xs round">
						<view class="icon text-df text-bold wanl-gray-dark">
							<text class="iconfont icon-sousuo"></text>
						</view>
						<swiper vertical autoplay circular interval="3000">
							<swiper-item @tap="handleSearch('')">
								<text class="text-white text-cut">搜索</text>
							</swiper-item>
							<swiper-item v-for="(item, index) in common.modulesData.searchModules" :key="item.keywords"
								@tap="handleSearch(item.keywords)">
								<text class="wanl-gray-dark text-cut">{{ item.keywords }}</text>
							</swiper-item>
						</swiper>
					</view>
					<view class="flex">
						<view class="text-xxl" @tap="$wanlshop.to('/pages/notice/notice')">
							<text class="iconfont icon-xiaoxizhongxin" style="font-size: 50rpx;"></text>
						</view>
					</view>
				</view>
				<view class="toolbar flex padding-lr-bj align-center">

				</view>
			</view>
		</view>
		<!-- 主体 -->

		<wanl-scroll-list ref="list" :option="{auto: true }" @load="load($event,'load')"
			@refresh="load($event,'refresh')">
			<wanl-shop-home :indexData="indexData" :windowHeight="windowHeight" :headHeight="headHeight"
				:headTop="headTop" :pageModules="common.modulesData.homeModules" :adData="common.adData" />

		</wanl-scroll-list>
		<!-- #ifdef APP-PLUS -->
		<wanl-appversion ref="appversion" @close="close"></wanl-appversion>
		<!-- #endif -->
		
		<u-modal v-model="showLoading" title="是否打开位置权限设置页面?" content="是否允许访问您的位置权限，用于员工打卡与获取附近客户？如拒绝授权获取地理位置,你将无法正常使用本App"
			:async-close="true" @confirm="confirm" @cancel="cancel" :show-cancel-button="true"></u-modal>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	import permision from "@/common/permission.js"
	import wanlShopHome from '@/components/wanl-shop/home';

	export default {
		components: {
			wanlShopHome
		},
		computed: {
			...mapState(['common', 'user', 'update'])
		},
		data() {
			return {
				showLoading: false,
				headHeight: 0,
				windowHeight: 0,
				headTop: 0,
				currentItemId: 'home',
				currentData: {},
				scrollLeft: 0,
				isModal: false,
				contentText: {
					contentdown: '下拉加载更多',
					contentrefresh: '加载中',
					contentnomore: '我是有底线的'
				},
				indexData: {
					article: [],
					doctor: [],
					goods: [],
					volunteer_activity: [],
					works_category: [],
				}
			};
		},
		async onLoad(options) {
			// 获取 departmentid 参数并存入缓存
			if (options && options.departmentid) {
				uni.setStorageSync('departmentid', options.departmentid);
				console.log('已保存 departmentid:', options.departmentid);
			}
			
			// #ifdef APP-PLUS
			plus.navigator.setFullscreen(false); 
			let checkSystemEnableLocation = permision.checkSystemEnableLocation();
			if(!checkSystemEnableLocation) {
				uni.request({
					url: '/publics/city/default',
					success: (ret) => {
						uni.setStorageSync('cityid', ret.data.areaid);
						uni.setStorageSync('city', ret.data.name);
						this.$store.commit('common/setState', {
							addressText:ret.data.name,
							cityId:ret.data.areaid,
						});
					}
				})
				return this.$wanlshop.msg('请打开手机位置信息')
			}
			var result = await permision.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
			console.log(result,2222)
			if (result == 1) { // 1 已获取授权 0 未获取授权 1 被永久拒绝授权
				this.$store.dispatch('common/getLocation').then(res=>{
					console.log(res,34444)
					uni.request({
						url: '/publics/city/default',
						data: {
							city: res
						},
						success: (ret) => {
							uni.setStorageSync('cityid', ret.data.areaid);
							uni.setStorageSync('city', ret.data.name);
							this.$store.commit('common/setState', {
								addressText:ret.data.name,
								cityId:ret.data.areaid,
							});
						}
					})
				})
			} else {
				// 没有权限或者被禁止
				this.showLoading = true;
			}
			// this.getPopUp();
			// #endif
		},
		async onShow() {
			// 检查 URL 参数中是否有 departmentid
			const pages = getCurrentPages();
			const currentPage = pages[pages.length - 1];
			if (currentPage && currentPage.options && currentPage.options.departmentid) {
				const newDepartmentId = currentPage.options.departmentid;
				const oldDepartmentId = uni.getStorageSync('departmentid');
				
				// 如果 departmentid 有更新，则更新缓存
				if (newDepartmentId !== oldDepartmentId) {
					uni.setStorageSync('departmentid', newDepartmentId);
					console.log('departmentid 已更新:', newDepartmentId);
				}
			}
			
			// #ifdef H5
			this.$store.dispatch('common/getLocation').then(res=>{
				uni.request({
					url: '/publics/city/default',
					data: {
						city: res
					},
					success: (ret) => {
						uni.setStorageSync('cityid', ret.data.areaid);
						uni.setStorageSync('city', ret.data.name);
						this.$store.commit('common/setState', {
							addressText:ret.data.name,
							cityId:ret.data.areaid,
						});
					}
				})
			})
			// #endif
			// 计算页面尺寸
			let sys = this.$wanlshop.wanlsys();
			this.headTop = sys.top;
			this.headHeight = sys.height;
			this.windowHeight = sys.windowHeight;
			setTimeout(() => {
				uni.setNavigationBarColor({
					frontColor: this.$store.state.common.modulesData.homeModules.page ?
						this.$store.state.common.modulesData.homeModules.page.style
						.navigationBarTextStyle : '',
					backgroundColor: this.$store.state.common.modulesData.homeModules.page ?
						this.$store.state.common.modulesData.homeModules.page.style
						.navigationBarBackgroundColor : ''
				});
			}, 200);
			if(this.$refs.list) {
				this.load({page:1},'refresh')
			}
		},
		methods: {
			cancel() {
				this.showLoading = false;
			},
			confirm() {
				permision.gotoAppPermissionSetting()
			},
			close() {
				this.checkHomePopup();
			},
			checkHomePopup() {
				// console.log("再次进去，case");
				uni.getStorage({
					key: "popUp-show-time",
					success: (res) => {
						// console.log("case 第二次进入，checkHomePopup有");
						// 24小时超时
						if (!res.data ||new Date().getTime() - res.data > 1000 * 60 * 60 * 0.025) {
							uni.setStorage({
								key: "popUp-show-time",
								data: new Date().getTime(),
							});
							// console.log("case 二次进入，超时，checkHomePopup");
							// #ifdef APP-PLUS
							if (this.$refs.appversion) {
								this.$refs.appversion.update()
							}
							// #endif
						} else {
							console.log("case er   else");
						}
					},
					fail: (err) => {
						// console.log("case 创建。fail");
						uni.setStorage({
							key: "popUp-show-time",
							data: new Date().getTime(),
						});
					},
				});
			},
			openPopAd() {
				// #ifdef APP-PLUS
				if (this.$refs.appversion) {
					this.$refs.appversion.update()
				}
				// #endif
				uni.setStorage({
					key: "popUp-show-time",
					data: new Date().getTime(),
				});
				// console.log("case 本地无，或超时重新创建");
			},

			getPopUp() {
				uni.getStorage({
					key: "popUp-show-time",
					success: (res) => {
						console.log(new Date().getTime() - res.data)
						// 24小时超时
						if (!res.data || new Date().getTime() - res.data > 1000 * 60 * 60 * 0.025) {
							// console.log("刚进入，本地有，且超时", "case");
							this.openPopAd();
						} else {
							// console.log("刚进入，时间没到", "case");
							this.checkHomePopup();
						}
					},
					fail: (err) => {
						// console.log("刚进入，本地无", "case");
						this.openPopAd();
					},
				});
			},
			async getHospital() {
				await uni.request({
					url: `/index/index`,
					success: res => {
						this.indexData = res.data;
					}
				});
			},
			load(event, key) {
				// #ifdef APP-PLUS
				if (this.$refs.appversion) {
					this.$refs.appversion.update()
				}
				// #endif
				this.getHospital();
				this.$refs.list.refreshSuccess({
					list: [],
					total: 0
				});
				this.$refs.list.showPullUp = false;
				this.$refs.list.showEmpty = false;
			},
			// 一下扫码
			scanCode() {
				// #ifndef H5
				uni.scanCode({
					success: res => {
						var QRcode = this.getUrlParam(res.result);
						switch (QRcode.QRtype) {
							case 'goods':
								this.onGoods(QRcode.id);
								break;
							case 'user':
								this.$wanlshop.to(`/pages/user/info?id=${QRcode.id}`);
								break;
							case 'category':
								this.$wanlshop.on('/pages/category');
								break;
							case 'page':
								this.$wanlshop.to(`/pages/page/index?id=${QRcode.id}`);
								break;
							case 'shop':
								this.onShop(QRcode.id);
								break;
							case 'live':
								// #ifdef APP-PLUS || MP-WEIXIN
								this.$wanlshop.auth(`/pages/shop/live/live`);
								// #endif
								// #ifndef APP-PLUS || MP-WEIXIN
								this.$wanlshop.msg('目前只开放App和微信小程序直播');
								// #endif
								break;
							case 'chat':
								this.toChat(QRcode.id);
								break;
						}
					}
				});
				// #endif
				// #ifdef H5
				this.$wanlshop.msg('暂不支持H5扫码');
				// #endif
			},
			// 解析Url
			getUrlParam(url) {
				var obj = {};
				var data = url.split('?')[1].split('&');
				for (var i = 0; i < data.length; i++) {
					var res = data[i].split('=');
					obj[res[0]] = res[1];
				}
				return obj;
			},
			// 搜索
			handleSearch(text) {
				this.$wanlshop.to(`/pages/page/search?type=goods&keywords=${text}`, 'fade-in', 100);
			}
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #F4F4F4;
	}

	.wanlshop-container {
		&__head {
			// position: fixed;
			// top: 0;
			// left: 0;
			// right: 0;
			z-index: 999;
			background-size: 100% auto;
			background-repeat: no-repeat;

			.navigater {
				height: 86rpx;
				padding-left: 25rpx;
				padding-right: 25rpx;
				/* #ifdef MP */
				padding-right: 220rpx;

				/* #endif */
				.search {
					flex: 1;
					background-color: transparent;
					height: 66rpx;
					border: 2rpx solid #fff;

					.icon {
						margin: 0 20rpx;
						color: #fff;
					}

					swiper {
						height: 100%;
						width: 100%;
						margin-right: 10rpx;

						swiper-item {
							display: flex;
							align-items: center;
						}
					}
				}
			}

			.toolbar {
				.scroll {
					flex: 1;
					white-space: nowrap;
					overflow: hidden;
					width: 100%;

					&__item {
						position: relative;
						z-index: 2;
						font-size: 28rpx;
						display: inline-flex;
						height: 58rpx;
						align-items: center;
						margin-right: 40rpx;

						&.action {
							position: relative;
							font-weight: bold;
							font-size: 30rpx;

							&::after {
								content: ' ';
								position: absolute;
								bottom: 0;
								left: 50%;
								transform: translateX(-50%);
								height: 4rpx;
								width: 30rpx;
								border-radius: 6rpx;
								background-color: #fff;
							}
						}
					}
				}

				.category {
					box-shadow: #eee -16rpx 0 16rpx -16rpx;
					height: 58rpx;
					font-size: 28rpx;
					padding-left: 25rpx;
				}
			}
		}

		&__main {
			position: relative;
			z-index: 99;
		}

		.WANL-MODAL {
			.cu-modal {
				&.top-modal {
					background: rgba(0, 0, 0, 0.6);
					text-align: inherit;

					.cu-dialog {
						background: #fff;
						border-radius: 0 0 18rpx 18rpx;

						.category {
							display: grid;
							grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
							grid-auto-flow: row dense;
							grid-gap: 16rpx;

							.item {
								display: flex;
								align-items: center;
								justify-content: center;
								padding: 12rpx 0;
								border: 2rpx solid transparent;

								&.action {
									background-color: transparent;
									border-color: #f40;
									color: #f40;
									font-weight: bold;
								}
							}
						}
					}
				}
			}
		}
	}
</style>